from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers

from verifications import constants
import logging
logger = logging.getLogger('django')
class CheckImageCodeSerializer(serializers.Serializer):
    # 这里是要校验字段
    image_code_id=serializers.UUIDField()
    text=serializers.CharField(min_length=4,max_length=4)

    def validate(self, attrs):
        # 取出真实的图片验证码
        image_code_id=attrs['image_code_id']
        text=attrs['text']
        redis_connect = get_redis_connection('verify_codes')
        real_text=redis_connect.get('img_%s' % image_code_id)

        if real_text is None:
            raise serializers.ValidationError('获取短信验证码错误')
        real_text = real_text.decode()
        if text.lower() !=real_text.lower():
            raise serializers.ValidationError('验证码错误')
        # 删除记录
        try:
            redis_connect.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)
        #　检查６０秒之内有无发送短信记录
        mobile=None
        try:
            mobile=self.context['view'].kwargs['mobile']
        except Exception as e:
            pass
        if mobile:
            send_flag=redis_connect.get('send_flag_%s' % mobile)
            if send_flag:
                raise serializers.ValidationError('发送短信验证码的频率过高')
        return attrs
